﻿using TinyGet.Models;
using TinyGet.Helpers;
using System.Linq;
using System.Linq.Expressions;
using System;

public class TinyGetRepository
{
    TinyGetDataContext db = new TinyGetDataContext();

    public TinyGetRepository()
    {
    }

    public TinyLink getLink(string hash)
    {
        try // search for URL with normal random hash
        {

            //TinyLink link = db.TinyLinks.Where(p => p.Hash.Equals(hash.ToLower())).Single();

            TinyLink link = new TinyLink();

            link = db.TinyLinks.Where(p => p.Hash.Equals(hash.ToLower())).Single();

            link.Visits++;
            db.SubmitChanges();
            return link;
        }
        catch (InvalidOperationException) // couldnt find one so it searchs here for a URL matching a custom name
        {
            try
            {
                TinyLink link = new TinyLink();
                link = db.TinyLinks.Where(p => p.Custom.Equals(hash.ToLower())).Single();
                link.Visits++;
                db.SubmitChanges();
                return link;
            }
            catch (InvalidOperationException) // hits this if both fail to return a URL
            {
                return new TinyLink();
            }

        }
    }

    public string addLink(string url, string custom)//added an option for a custom name at the end of the URL (allowed to be null)
    {

        if (url.IndexOf("://") == -1) url = "http://" + url;

        TinyLink link = new TinyLink();

        if (custom != null) //using a custom hash instead of random
        {
            link.Url = url.ToLower();
            link.Hash = "";
            link.Custom = custom.ToLower();
            link.AbusiveFlag = false;
            link.AbusiveVotes = 0;
            link.Visits = 0;
            link.Votes = 0;
            link.Created = DateTime.Now;
            db.TinyLinks.InsertOnSubmit(link);
            db.SubmitChanges();

            string hash = Base36.Encode(link.ID).ToLower();
            link.Hash = hash;
            db.SubmitChanges();

            return link.Custom;
        }
        else // using random hash no custom name
        {
            link.Url = url.ToLower();
            link.Hash = "";
            link.AbusiveFlag = false;
            link.AbusiveVotes = 0;
            link.Visits = 0;
            link.Votes = 0;
            link.Created = DateTime.Now;
            db.TinyLinks.InsertOnSubmit(link);
            db.SubmitChanges();

            string hash = Base36.Encode(link.ID).ToLower();
            link.Hash = hash;
            db.SubmitChanges();

            return hash;
        }
    }
}